<template>
  <el-dialog
    :model-value="visible"
    class="create-requirement-dialog"
    width="1400px"
    align-center
    :close-on-click-modal="false"
    :show-close="false"
    :before-close="handleClose"
    @update:model-value="(value: boolean) => emit('update:visible', value)"
  >
    <template #header>
      <div class="dialog-header-wrapper">
        <div class="dialog-header-title">新建需求</div>
        <div class="dialog-header-actions">
          <el-button @click="handleClose">关闭</el-button>
          <el-button
            type="primary"
            :loading="saving"
            :disabled="!canCreate"
            @click="handleCreate"
          >
            确认
          </el-button>
        </div>
      </div>
    </template>

    <div class="create-requirement">
      <div class="detail-body">
        <div class="primary-column">
          <div class="detail-header">
            <div class="header-top">
              <div class="status-tags">
                <el-tag
                  v-if="formData.status"
                  :type="getStatusTypeWrapper(formData.status)"
                  size="small"
                >
                  {{ getStatusTextWrapper(formData.status) }}
                </el-tag>
                <el-tag
                  v-if="formData.priority"
                  :type="getPriorityTypeWrapper(formData.priority)"
                  size="small"
                >
                  {{ getPriorityTextWrapper(formData.priority) }}
                </el-tag>
                <el-tag v-if="formData.requirement_type" size="small" type="info">
                  {{ getTypeTextWrapper(formData.requirement_type) }}
                </el-tag>
              </div>
            </div>

            <div class="title-section" ref="titleFieldRef">
              <div class="field-label">
                <span>需求标题</span>
                <span class="required">*</span>
              </div>
              <el-input
                v-model="formData.title"
                placeholder="请输入需求标题"
                maxlength="200"
                show-word-limit
                size="large"
                class="title-input"
                :class="{ 'field-error': fieldErrors.title }"
                @input="clearFieldErrorWrapper('title')"
              />
              <div v-if="fieldErrors.title" class="error-message">{{ fieldErrors.title }}</div>
            </div>
          </div>

          <section class="section-card tabs-card">
            <el-tabs v-model="contentTab" class="content-tabs">
              <el-tab-pane label="需求描述" name="description">
                <div class="tab-content-wrapper">
                  <EnhancedRichTextEditor
                    v-model="formData.description"
                    placeholder="请描述需求内容..."
                    :min-height="400"
                  />
                </div>
              </el-tab-pane>

              <el-tab-pane label="验收标准" name="acceptance">
                <div class="tab-content-wrapper">
                  <el-input
                    v-model="formData.acceptance_criteria"
                    type="textarea"
                    placeholder="请填写验收标准"
                    :rows="6"
                    maxlength="2000"
                    show-word-limit
                    resize="vertical"
                  />
                </div>
              </el-tab-pane>

              <el-tab-pane label="商业价值" name="business">
                <div class="tab-content-wrapper">
                  <el-input
                    v-model="formData.business_value"
                    type="textarea"
                    placeholder="请描述该需求的商业价值（可选）"
                    :rows="5"
                    maxlength="1000"
                    show-word-limit
                    resize="vertical"
                  />
                </div>
              </el-tab-pane>
            </el-tabs>
          </section>

          <!-- 关联页签 - 移动到富文本编辑器下面 -->
          <section class="section-card associations-card">
            <el-tabs v-model="associationSubTab" type="border-card" class="association-sub-tabs">
              <!-- 关联任务子页签 -->
              <el-tab-pane label="关联任务" name="tasks">
                <div class="sub-tab-content">
                  <div class="tab-header">
                    <div class="header-info">
                      <span class="item-count">已选择任务（{{ selectedTasks.length }}）</span>
                    </div>
                    <div class="header-actions">
                      <el-button
                        type="primary"
                        size="small"
                        @click="handleAddTask"
                      >
                        <el-icon><Plus /></el-icon>
                        添加任务
                      </el-button>
                    </div>
                  </div>

                  <div class="items-list">
                    <el-table
                      v-if="selectedTasks.length > 0"
                      :data="selectedTasks"
                      size="default"
                      border
                      stripe
                      :style="{ width: '100%' }"
                    >
                      <el-table-column prop="title" label="任务标题" min-width="200" show-overflow-tooltip />
                      <el-table-column prop="status" label="状态" width="100">
                        <template #default="{ row }">
                          <el-tag :type="getTaskStatusType(row.status)" size="small">
                            {{ getTaskStatusName(row.status) }}
                          </el-tag>
                        </template>
                      </el-table-column>
                      <el-table-column prop="priority" label="优先级" width="90">
                        <template #default="{ row }">
                          <el-tag :type="getTaskPriorityType(row.priority)" size="small">
                            {{ getTaskPriorityName(row.priority) }}
                          </el-tag>
                        </template>
                      </el-table-column>
                      <el-table-column label="负责人" width="150" show-overflow-tooltip>
                        <template #default="{ row }">
                          <UserDisplay
                            :user-id="row.assignee_id"
                            :user-name="row.assignee_name"
                            :show-avatar="true"
                            size="small"
                          />
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" width="120" fixed="right">
                        <template #default="{ row }">
                          <el-button
                            link
                            type="danger"
                            size="small"
                            @click="handleRemoveTask(row)"
                          >
                            移除
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <el-empty v-else description='暂无关联任务，点击"添加任务"进行关联' :image-size="80" />
                  </div>
                </div>
              </el-tab-pane>

              <!-- 关联缺陷子页签 -->
              <el-tab-pane label="关联缺陷" name="defects">
                <div class="sub-tab-content">
                  <div class="tab-header">
                    <div class="header-info">
                      <span class="item-count">已选择缺陷（{{ selectedDefects.length }}）</span>
                    </div>
                    <div class="header-actions">
                      <el-button
                        type="primary"
                        size="small"
                        @click="handleAddDefect"
                      >
                        <el-icon><Plus /></el-icon>
                        添加缺陷
                      </el-button>
                    </div>
                  </div>

                  <div class="items-list">
                    <el-table
                      v-if="selectedDefects.length > 0"
                      :data="selectedDefects"
                      size="default"
                      border
                      stripe
                      :style="{ width: '100%' }"
                    >
                      <el-table-column prop="title" label="缺陷标题" min-width="200" show-overflow-tooltip />
                      <el-table-column prop="status" label="状态" width="100">
                        <template #default="{ row }">
                          <el-tag :type="getDefectStatusType(row.status)" size="small">
                            {{ getDefectStatusName(row.status) }}
                          </el-tag>
                        </template>
                      </el-table-column>
                      <el-table-column prop="severity" label="严重程度" width="100">
                        <template #default="{ row }">
                          <el-tag :type="getDefectSeverityType(row.severity)" size="small">
                            {{ getDefectSeverityName(row.severity) }}
                          </el-tag>
                        </template>
                      </el-table-column>
                      <el-table-column prop="priority" label="优先级" width="90">
                        <template #default="{ row }">
                          <el-tag :type="getDefectPriorityType(row.priority)" size="small">
                            {{ getDefectPriorityName(row.priority) }}
                          </el-tag>
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" width="120" fixed="right">
                        <template #default="{ row }">
                          <el-button
                            link
                            type="danger"
                            size="small"
                            @click="handleRemoveDefect(row)"
                          >
                            移除
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <el-empty v-else description='暂无关联缺陷，点击"添加缺陷"进行关联' :image-size="80" />
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </section>
        </div>

        <aside class="side-column">
          <section class="info-card">
            <div class="info-card-title">基础字段</div>
            <div class="info-form-group" v-if="defaultParentId && defaultParentName">
              <label class="info-label">父需求</label>
              <div class="parent-info-display">
                <el-tag type="info" size="default">
                  <el-icon><ArrowLeft /></el-icon>
                  {{ defaultParentName }}
                </el-tag>
                <span class="parent-hint">（新建的子需求）</span>
              </div>
            </div>
            <div class="info-form-group" ref="statusFieldRef">
              <label class="info-label">状态 <span class="required">*</span></label>
              <el-select
                v-model="formData.status"
                placeholder="请选择状态"
                size="default"
                :class="{ 'field-error': fieldErrors.status }"
                @change="clearFieldErrorWrapper('status')"
              >
                <el-option
                  v-for="option in statusOptions"
                  :key="option.value"
                  :value="option.value"
                  :label="option.label"
                />
              </el-select>
              <div v-if="fieldErrors.status" class="error-message">{{ fieldErrors.status }}</div>
            </div>
            <div class="info-form-group">
              <label class="info-label">优先级</label>
              <el-select
                v-model="formData.priority"
                placeholder="请选择优先级"
                size="default"
              >
                <el-option
                  v-for="option in priorityOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </div>
            <div class="info-form-group">
              <label class="info-label">需求类型</label>
              <el-select
                v-model="formData.requirement_type"
                placeholder="请选择类型"
                size="default"
              >
                <el-option
                  v-for="option in typeOptions"
                  :key="option.value"
                  :value="option.value"
                  :label="option.label"
                />
              </el-select>
            </div>
            <div class="info-form-group">
              <label class="info-label">需求来源</label>
              <el-select
                v-model="formData.source"
                placeholder="请选择来源"
                size="default"
              >
                <el-option
                  v-for="option in sourceOptions"
                  :key="option.value"
                  :value="option.value"
                  :label="option.label"
                />
              </el-select>
            </div>
            <div class="info-form-group" ref="projectIdFieldRef">
              <label class="info-label">所属项目 <span class="required">*</span></label>
              <el-select
                v-model="formData.project_id"
                placeholder="请选择项目"
                filterable
                size="default"
                :disabled="!!defaultParentId"
                :class="{ 'field-error': fieldErrors.project_id }"
                @change="clearFieldErrorWrapper('project_id')"
              >
                <el-option
                  v-for="project in projects"
                  :key="project.id"
                  :label="project.name"
                  :value="project.id"
                />
              </el-select>
              <div v-if="fieldErrors.project_id" class="error-message">{{ fieldErrors.project_id }}</div>
            </div>
            <div class="info-form-group">
              <label class="info-label">关联版本</label>
              <el-select
                v-model="formData.version_ids"
                multiple
                filterable
                collapse-tags
                collapse-tags-tooltip
                placeholder="请先选择项目"
                :disabled="!formData.project_id"
                :loading="versionsLoading"
                @visible-change="handleVersionSelectVisibleChange"
              >
                <el-option
                  v-for="version in availableVersionOptions"
                  :key="version.id"
                  :label="getVersionOptionLabelWrapper(version)"
                  :value="version.id"
                />
              </el-select>
            </div>
            <div class="info-form-group">
              <label class="info-label">需求标签</label>
              <el-select
                v-model="formData.tags"
                multiple
                filterable
                allow-create
                default-first-option
                collapse-tags
                collapse-tags-tooltip
                placeholder="请选择标签或输入新标签"
                size="default"
              >
                <el-option
                  v-for="tag in commonTagOptions"
                  :key="tag"
                  :label="tag"
                  :value="tag"
                />
              </el-select>
            </div>
          </section>

          <section class="info-card">
            <div class="info-card-title">人员</div>
            <div class="info-form-group" ref="reporterIdFieldRef">
              <label class="info-label">报告人 <span class="required">*</span></label>
              <div class="user-select-wrapper">
                <el-select
                  v-model="formData.reporter_id"
                  placeholder="请先选择项目"
                  filterable
                  clearable
                  size="default"
                  :disabled="!formData.project_id"
                  :class="{ 'field-error': fieldErrors.reporter_id, 'has-selected-user': selectedReporter }"
                  @change="clearFieldErrorWrapper('reporter_id')"
                >
                  <el-option
                    v-for="user in availableUsers"
                    :key="user.id"
                    :label="user.name || user.username"
                    :value="user.id"
                  >
                    <UserDisplay
                      :user="user"
                      :show-avatar="true"
                      size="small"
                    />
                  </el-option>
                </el-select>
                <div v-if="selectedReporter" class="selected-user-overlay">
                  <UserDisplay
                    :user="selectedReporter"
                    :show-avatar="true"
                    size="small"
                  />
                </div>
              </div>
              <div v-if="fieldErrors.reporter_id" class="error-message">{{ fieldErrors.reporter_id }}</div>
            </div>
            <div class="info-form-group">
              <label class="info-label">负责人</label>
              <div class="user-select-wrapper">
                <el-select
                  v-model="formData.assignee_id"
                  placeholder="请先选择项目"
                  filterable
                  clearable
                  size="default"
                  :disabled="!formData.project_id"
                  :class="{ 'has-selected-user': selectedAssignee }"
                >
                  <el-option
                    v-for="user in availableUsers"
                    :key="user.id"
                    :label="user.name || user.username"
                    :value="user.id"
                  >
                    <UserDisplay
                      :user="user"
                      :show-avatar="true"
                      size="small"
                    />
                  </el-option>
                </el-select>
                <div v-if="selectedAssignee" class="selected-user-overlay">
                  <UserDisplay
                    :user="selectedAssignee"
                    :show-avatar="true"
                    size="small"
                  />
                </div>
              </div>
            </div>
          </section>

          <section class="info-card">
            <div class="info-card-title">时间与工时</div>
            <div class="info-form-group">
              <label class="info-label">计划开始时间</label>
              <el-date-picker
                v-model="formData.start_date"
                type="datetime"
                value-format="YYYY-MM-DDTHH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择开始日期时间"
                size="default"
                style="width: 100%"
              />
            </div>
            <div class="info-form-group">
              <label class="info-label">计划完成时间</label>
              <el-date-picker
                v-model="formData.due_date"
                type="datetime"
                value-format="YYYY-MM-DDTHH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择截止日期时间"
                size="default"
                style="width: 100%"
              />
            </div>
            <div class="info-form-group">
              <label class="info-label">预估工时（小时）</label>
              <el-input-number
                v-model="formData.estimated_effort"
                :min="0"
                :step="0.5"
                :precision="1"
                size="default"
                style="width: 100%"
                controls-position="right"
              />
            </div>
          </section>
        </aside>
      </div>
    </div>

    <!-- 任务选择对话框 -->
    <TaskSelectorDialog
      v-model="taskSelectorVisible"
      :project-id="formData.project_id"
      @confirm="handleTaskSelected"
    />

    <!-- 缺陷选择对话框 -->
    <DefectSelectorDialog
      v-model="defectSelectorVisible"
      :project-id="formData.project_id"
      @confirm="handleDefectSelected"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, ArrowLeft } from '@element-plus/icons-vue'
import EnhancedRichTextEditor from '@/components/common/EnhancedRichTextEditor.vue'
import TaskSelectorDialog from '@/components/version/TaskSelectorDialog.vue'
import DefectSelectorDialog from '@/components/version/DefectSelectorDialog.vue'
import {
  createRequirement,
  RequirementPriority,
  RequirementSource,
  RequirementType
} from '@/api/requirements'
import { useRequirementOptions } from '@/composables/useRequirementOptions'
import { ResponseParser } from '@/utils/responseParser'
import type { Task } from '@/api/task'
import type { Defect } from '@/api/defect'
import taskAPI from '@/api/task'
import { batchUpdateDefectsRequirement } from '@/api/defect'
import { useTaskStates } from '@/composables/useTaskStates'
import { useDefectStates } from '@/composables/useDefectStates'
import { useDefectOptions } from '@/composables/useDefectOptions'
import UserDisplay from '@/components/ui/UserDisplay.vue'
import {
  type StatusOption,
  type BasicOption,
  type ProjectOption,
  type VersionOption,
  getStatusType,
  getStatusText,
  getPriorityType,
  getPriorityText,
  getTypeText,
  getVersionOptionLabel,
  clearFieldError,
  scrollToField
} from '../utils/requirementUtils'
import type { User } from '@/types/user'
import { useRequirementsStore } from '@/stores/requirements'

interface Props {
  visible: boolean
  projects: ProjectOption[]
  users: User[]
  statusOptions: StatusOption[]
  priorityOptions: BasicOption[]
  commonTags?: string[]
  currentUserId?: string
  defaultProjectId?: string
  defaultParentId?: string | null
  defaultParentName?: string
  defaultStatus?: string
  versionOptions?: VersionOption[]
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'created', requirementId: string): void
  (e: 'request-version-options'): void
}

const props = withDefaults(defineProps<Props>(), {
  commonTags: () => [],
  defaultProjectId: '',
  defaultParentId: null,
  defaultParentName: '',
  defaultStatus: '',
  versionOptions: () => []
})

const emit = defineEmits<Emits>()

const contentTab = ref('description')
const associationSubTab = ref('tasks')
const saving = ref(false)
const versionsLoading = ref(false)
const taskSelectorVisible = ref(false)
const defectSelectorVisible = ref(false)
const selectedTasks = ref<Task[]>([])
const selectedDefects = ref<Defect[]>([])

// 字段错误信息
const fieldErrors = reactive<Record<string, string>>({})

// 字段引用
const titleFieldRef = ref<HTMLElement | null>(null)
const statusFieldRef = ref<HTMLElement | null>(null)
const projectIdFieldRef = ref<HTMLElement | null>(null)
const reporterIdFieldRef = ref<HTMLElement | null>(null)

const { getStateName: getTaskStateName } = useTaskStates()
const { getStateName: getDefectStateName } = useDefectStates()
const { getSeverityName: getSeverityNameFromOptions, getPriorityName: getPriorityNameFromOptions } = useDefectOptions()
const { formattedTypeOptions, formattedSourceOptions } = useRequirementOptions()
const requirementsStore = useRequirementsStore()

const typeOptions = formattedTypeOptions
const sourceOptions = formattedSourceOptions

// 本地用户列表（项目成员）
const localUsers = ref<User[]>([])

// 计算可用的用户列表（优先使用本地项目成员，如果没有则使用props.users作为后备）
const availableUsers = computed(() => {
  // 如果已选择项目且有项目成员，使用项目成员
  if (formData.project_id && localUsers.value.length > 0) {
    return localUsers.value
  }
  // 否则返回空数组（项目必先选）
  return []
})

// 计算选中的用户对象
const selectedReporter = computed(() => {
  if (!formData.reporter_id) return null
  return availableUsers.value.find((user: User) => user.id === formData.reporter_id) || null
})

const selectedAssignee = computed(() => {
  if (!formData.assignee_id) return null
  return availableUsers.value.find((user: User) => user.id === formData.assignee_id) || null
})

const formData = reactive({
  title: '',
  description: '',
  acceptance_criteria: '',
  business_value: '',
  requirement_type: (typeOptions.value[0]?.value as RequirementType) ?? RequirementType.FUNCTIONAL,
  status: props.defaultStatus || '',
  priority: RequirementPriority.MEDIUM,
  source: (sourceOptions.value[0]?.value as RequirementSource) || 'internal',
  project_id: props.defaultProjectId || '',
  assignee_id: '',
  reporter_id: props.currentUserId || '',
  estimated_effort: undefined as number | undefined,
  start_date: '',
  due_date: '',
  tags: [] as string[],
  version_ids: [] as string[],
  parent_id: (props.defaultParentId || '') as string
})

const commonTagOptions = computed(() => {
  const tags = new Set<string>(props.commonTags || [])
  formData.tags.forEach(tag => tags.add(tag))
  return Array.from(tags)
})

const availableVersionOptions = computed<VersionOption[]>(() => {
  const projectId = formData.project_id
  if (!projectId) {
    // 如果没有选择项目，返回空数组（项目必先选）
    return []
  }
  const selectedIds = new Set(formData.version_ids)
  return (props.versionOptions || []).filter(option => {
    // 如果已选中的版本，保留（即使项目ID不匹配，也允许保留已选中的）
    if (selectedIds.has(option.id)) {
      return true
    }
    // 只显示属于当前项目的版本（必须有项目ID且匹配）
    return option.project_id === projectId
  })
})

const canCreate = computed(() => {
  return Boolean(
    formData.title.trim() &&
    formData.project_id &&
    formData.status
  )
})

// 使用共享工具函数的包装函数
const getStatusTypeWrapper = (status: string) => getStatusType(status, props.statusOptions)
const getStatusTextWrapper = (status: string) => getStatusText(status, props.statusOptions)
const getPriorityTypeWrapper = (priority: string) => getPriorityType(priority, props.priorityOptions)
const getPriorityTextWrapper = (priority: string) => getPriorityText(priority, props.priorityOptions)
const getTypeTextWrapper = (type: string) => getTypeText(type)
const getVersionOptionLabelWrapper = (option: VersionOption) => getVersionOptionLabel(option)
const clearFieldErrorWrapper = (field: string) => clearFieldError(field, fieldErrors)
const scrollToFieldWrapper = (fieldName: string) => scrollToField(fieldName, {
  titleFieldRef,
  statusFieldRef,
  projectIdFieldRef,
  reporterIdFieldRef
})

function handleVersionSelectVisibleChange(visible: boolean) {
  if (visible) {
    emit('request-version-options')
  }
}

function handleClose() {
  emit('update:visible', false)
}

function resetForm() {
  formData.title = ''
  formData.description = ''
  formData.acceptance_criteria = ''
  formData.business_value = ''
  formData.requirement_type = (typeOptions.value[0]?.value as RequirementType) ?? RequirementType.FUNCTIONAL
  formData.status = props.defaultStatus || props.statusOptions[0]?.value || ''
  formData.priority = (props.priorityOptions[0]?.value as RequirementPriority) || RequirementPriority.MEDIUM
  formData.source = (sourceOptions.value[0]?.value as RequirementSource) || 'internal'
  formData.project_id = props.defaultProjectId || ''
  formData.assignee_id = ''
  formData.reporter_id = props.currentUserId || ''
  formData.estimated_effort = undefined
  formData.start_date = ''
  formData.due_date = ''
  formData.tags = []
  formData.version_ids = []
  formData.parent_id = props.defaultParentId || ''
  contentTab.value = 'description'
  associationSubTab.value = 'tasks'
  selectedTasks.value = []
  selectedDefects.value = []
  // 清除错误信息
  Object.keys(fieldErrors).forEach(key => delete fieldErrors[key])
}

// 监听父需求ID变化
watch(() => props.defaultParentId, (newParentId) => {
  if (newParentId) {
    formData.parent_id = newParentId
    // 如果有父需求，自动设置项目ID为父需求的项目ID
    if (props.defaultProjectId) {
      formData.project_id = props.defaultProjectId
    }
  }
}, { immediate: true })

// 监听父需求名称变化
watch(() => props.defaultParentName, () => {
  // 父需求名称变化时不需要更新表单数据，只需要显示
}, { immediate: true })

// 监听默认状态变化
watch(() => props.defaultStatus, (newStatus) => {
  if (newStatus && props.visible) {
    formData.status = newStatus
  }
}, { immediate: true })

// 监听默认项目ID变化
watch(() => props.defaultProjectId, (newProjectId) => {
  if (newProjectId && props.visible && !formData.project_id) {
    formData.project_id = newProjectId
  }
}, { immediate: true })

// 监听项目ID变化，动态加载项目成员
watch(() => formData.project_id, async (newProjectId, oldProjectId) => {
  // 如果项目ID变化，清空已选择的用户和版本（如果它们不属于新项目）
  if (newProjectId !== oldProjectId) {
    // 加载新项目的成员
    if (newProjectId) {
      try {
        localUsers.value = await requirementsStore.loadUsersForProject(newProjectId)
        // 如果当前选择的报告人或负责人不在新项目的成员列表中，清空选择
        if (formData.reporter_id && !localUsers.value.find(u => u.id === formData.reporter_id)) {
          formData.reporter_id = props.currentUserId || ''
        }
        if (formData.assignee_id && !localUsers.value.find(u => u.id === formData.assignee_id)) {
          formData.assignee_id = ''
        }
        
        // 清空不属于新项目的版本选择
        if (formData.version_ids && formData.version_ids.length > 0) {
          const validVersionIds = (props.versionOptions || [])
            .filter(option => option.project_id === newProjectId)
            .map(option => option.id)
          const selectedValidVersions = formData.version_ids.filter(id => validVersionIds.includes(id))
          if (selectedValidVersions.length !== formData.version_ids.length) {
            formData.version_ids = selectedValidVersions
          }
        }
      } catch (error) {
        console.error('加载项目成员失败:', error)
        localUsers.value = []
      }
    } else {
      // 如果没有选择项目，清空用户列表、已选择的用户和版本
      localUsers.value = []
      formData.reporter_id = props.currentUserId || ''
      formData.assignee_id = ''
      formData.version_ids = []
    }
  }
}, { immediate: true })

// 任务和缺陷关联相关函数
const handleAddTask = () => {
  taskSelectorVisible.value = true
}

const handleTaskSelected = (tasks: Task[]) => {
  if (!tasks.length) return
  
  const existingTaskIds = new Set(selectedTasks.value.map(t => t.id))
  const newTasks = tasks.filter(task => !existingTaskIds.has(task.id))
  selectedTasks.value = [...selectedTasks.value, ...newTasks]
  taskSelectorVisible.value = false
}

const handleRemoveTask = (task: Task) => {
  selectedTasks.value = selectedTasks.value.filter(t => t.id !== task.id)
}

const handleAddDefect = () => {
  defectSelectorVisible.value = true
}

const handleDefectSelected = (defects: Defect[]) => {
  if (!defects.length) return
  
  const existingDefectIds = new Set(selectedDefects.value.map(d => d.id))
  const newDefects = defects.filter(defect => !existingDefectIds.has(defect.id))
  selectedDefects.value = [...selectedDefects.value, ...newDefects]
  defectSelectorVisible.value = false
}

const handleRemoveDefect = (defect: Defect) => {
  selectedDefects.value = selectedDefects.value.filter(d => d.id !== defect.id)
}

// 任务状态辅助函数
function getTaskStatusType(status?: string): 'info' | 'success' | 'warning' | 'danger' {
  if (!status) return 'info'
  const statusName = getTaskStateName(status)
  const lower = statusName.toLowerCase()
  if (lower.includes('完成') || lower.includes('done') || lower.includes('closed')) return 'success'
  if (lower.includes('进行') || lower.includes('progress') || lower.includes('doing')) return 'warning'
  if (lower.includes('取消') || lower.includes('cancel')) return 'info'
  return 'info'
}

function getTaskStatusName(status?: string): string {
  if (!status) return ''
  return getTaskStateName(status)
}

function getTaskPriorityType(priority?: string): 'info' | 'success' | 'warning' | 'danger' {
  if (!priority) return 'info'
  const lower = priority.toLowerCase()
  if (lower === 'high' || lower === 'urgent' || lower === 'critical') return 'danger'
  if (lower === 'medium' || lower === 'normal') return 'warning'
  return 'info'
}

// 任务优先级名称映射 - 从任务优先级API获取，这里作为后备方案
// 实际应该从任务优先级管理模块获取，但为了简化，暂时保留映射
function getTaskPriorityName(priority?: string): string {
  if (!priority) return ''
  // TODO: 应该从任务优先级管理模块获取，而不是硬编码
  // 这里暂时保留作为后备方案，实际应该使用 useTaskOptions 或类似 composable
  const map: Record<string, string> = {
    'lowest': '最低',
    'low': '低',
    'medium': '中',
    'high': '高',
    'highest': '最高',
    'urgent': '紧急',
    'critical': '严重'
  }
  return map[priority.toLowerCase()] || priority
}

// 缺陷状态辅助函数
function getDefectStatusType(status?: string): 'info' | 'success' | 'warning' | 'danger' {
  if (!status) return 'info'
  const statusName = getDefectStateName(status)
  const lower = statusName.toLowerCase()
  if (lower.includes('已解决') || lower.includes('resolved') || lower.includes('closed')) return 'success'
  if (lower.includes('进行') || lower.includes('progress') || lower.includes('fixing')) return 'warning'
  if (lower.includes('新建') || lower.includes('new') || lower.includes('open')) return 'info'
  return 'info'
}

function getDefectStatusName(status?: string): string {
  if (!status) return ''
  return getDefectStateName(status)
}

function getDefectSeverityType(severity?: string): 'info' | 'success' | 'warning' | 'danger' {
  if (!severity) return 'info'
  const severityName = getSeverityNameFromOptions(severity)
  const lower = severityName.toLowerCase()
  if (lower.includes('严重') || lower.includes('critical') || lower.includes('致命')) return 'danger'
  if (lower.includes('高') || lower.includes('high') || lower.includes('major')) return 'warning'
  return 'info'
}

function getDefectSeverityName(severity?: string): string {
  if (!severity) return ''
  return getSeverityNameFromOptions(severity)
}

function getDefectPriorityType(priority?: string): 'info' | 'success' | 'warning' | 'danger' {
  if (!priority) return 'info'
  const priorityName = getPriorityNameFromOptions(priority)
  const lower = priorityName.toLowerCase()
  if (lower.includes('高') || lower.includes('high') || lower.includes('urgent')) return 'danger'
  if (lower.includes('中') || lower.includes('medium') || lower.includes('normal')) return 'warning'
  return 'info'
}

function getDefectPriorityName(priority?: string): string {
  if (!priority) return ''
  return getPriorityNameFromOptions(priority)
}

// 关联任务和缺陷
async function associateTasksAndDefects(requirementId: string) {
  // 关联任务
  if (selectedTasks.value.length > 0) {
    try {
      await Promise.allSettled(
        selectedTasks.value.map(task =>
          taskAPI.updateTask(task.id, { requirement_id: requirementId }).catch(error => {
            console.error(`关联任务 ${task.id} 失败:`, error)
            return null
          })
        )
      )
    } catch (error) {
      console.error('关联任务失败:', error)
    }
  }
  
  // 关联缺陷
  if (selectedDefects.value.length > 0) {
    try {
      const defectIds = selectedDefects.value.map(d => d.id)
      await batchUpdateDefectsRequirement(defectIds, requirementId)
    } catch (error) {
      console.error('关联缺陷失败:', error)
    }
  }
}

// 验证必填字段并定位到第一个错误字段
function validateRequiredFields(): boolean {
  // 清除之前的错误
  Object.keys(fieldErrors).forEach(key => delete fieldErrors[key])
  
  const errors: Record<string, string> = {}
  
  // 验证标题
  if (!formData.title.trim()) {
    errors.title = '请填写需求标题'
  }
  
  // 验证项目ID
  if (!formData.project_id) {
    errors.project_id = '请选择所属项目'
  }
  
  // 验证报告人
  const reporterId = formData.reporter_id || props.currentUserId
  if (!reporterId) {
    errors.reporter_id = '请选择报告人'
  }
  
  // 验证状态
  if (!formData.status) {
    errors.status = '请选择状态'
  }
  
  // 设置错误信息
  Object.assign(fieldErrors, errors)
  
  // 如果有错误，定位到第一个错误字段
  if (Object.keys(errors).length > 0) {
    const firstErrorField = Object.keys(errors)[0]
    scrollToFieldWrapper(firstErrorField)
    ElMessage.warning('请完善必填字段')
    return false
  }
  
  return true
}

async function handleCreate() {
  // 验证必填字段
  if (!validateRequiredFields()) {
    return
  }
  
  const title = formData.title.trim()
  const projectId = formData.project_id
  const reporterId = formData.reporter_id || props.currentUserId

  // 检查各字段长度
  const MAX_DESCRIPTION_LENGTH = 100000
  const MAX_ACCEPTANCE_LENGTH = 5000
  const MAX_BUSINESS_LENGTH = 2000
  
  const description = formData.description || ''
  const acceptance_criteria = formData.acceptance_criteria || ''
  const business_value = formData.business_value || ''
  
  if (description.length > MAX_DESCRIPTION_LENGTH) {
    ElMessage.warning(`需求描述内容过长（${description.length} 字符），最多支持 ${MAX_DESCRIPTION_LENGTH} 字符，请精简内容后重试`)
    return
  }
  
  if (acceptance_criteria.length > MAX_ACCEPTANCE_LENGTH) {
    ElMessage.warning(`验收标准内容过长（${acceptance_criteria.length} 字符），最多支持 ${MAX_ACCEPTANCE_LENGTH} 字符，请精简内容后重试`)
    return
  }
  
  if (business_value.length > MAX_BUSINESS_LENGTH) {
    ElMessage.warning(`商业价值内容过长（${business_value.length} 字符），最多支持 ${MAX_BUSINESS_LENGTH} 字符，请精简内容后重试`)
    return
  }

  saving.value = true
  try {
    // 构建请求数据，确保必填字段始终存在
    const payload: any = {
      title: title,
      project_id: projectId,
      reporter_id: reporterId,
      status: formData.status,
      requirement_type: formData.requirement_type || (typeOptions.value[0]?.value as RequirementType) || RequirementType.FUNCTIONAL,
      priority: formData.priority || RequirementPriority.MEDIUM,
      source: formData.source || (sourceOptions.value[0]?.value as RequirementSource) || 'internal'
    }
    
    // 可选字段
    if (description) {
      payload.description = description
    }
    if (acceptance_criteria) {
      payload.acceptance_criteria = acceptance_criteria
    }
    if (business_value) {
      payload.business_value = business_value
    }
    if (formData.assignee_id) {
      payload.assignee_id = formData.assignee_id
    }
    if (formData.estimated_effort !== undefined && formData.estimated_effort !== null) {
      payload.estimated_effort = formData.estimated_effort
    }
    if (formData.start_date) {
      // 将日期格式（YYYY-MM-DD）转换为 datetime 格式（YYYY-MM-DDTHH:mm:ss）
      if (formData.start_date.match(/^\d{4}-\d{2}-\d{2}$/)) {
        payload.start_date = `${formData.start_date}T00:00:00`
      } else {
        payload.start_date = formData.start_date
      }
    }
    if (formData.due_date) {
      // 将日期格式（YYYY-MM-DD）转换为 datetime 格式（YYYY-MM-DDTHH:mm:ss）
      if (formData.due_date.match(/^\d{4}-\d{2}-\d{2}$/)) {
        payload.due_date = `${formData.due_date}T00:00:00`
      } else {
        payload.due_date = formData.due_date
      }
    }
    if (formData.tags && formData.tags.length > 0) {
      payload.tags = formData.tags
    }
    
    // 如果有父需求ID，添加到请求数据中
    if (formData.parent_id) {
      payload.parent_id = formData.parent_id
    }
    
    const response = await createRequirement(payload)

    const parsed = ResponseParser.parseResponse(response)
    if (!parsed.success) {
      throw new Error(parsed.message || '创建失败')
    }

    const createdId = (parsed.data as any)?.id || ''
    
    // 创建成功后关联任务和缺陷
    if (createdId && (selectedTasks.value.length > 0 || selectedDefects.value.length > 0)) {
      try {
        await associateTasksAndDefects(createdId)
      } catch (error) {
        console.error('关联任务和缺陷失败:', error)
        // 即使关联失败，也不影响需求的创建成功提示
      }
    }
    
    ElMessage.success('创建成功')
    if (createdId) {
      emit('created', createdId)
    }
    resetForm()
    emit('update:visible', false)
  } catch (error) {
    const message = ResponseParser.extractMessage(error) || '创建失败'
    ElMessage.error(message)
  } finally {
    saving.value = false
  }
}

watch(
  () => props.visible,
  (value) => {
    if (value) {
      resetForm()
      // 确保报告人默认为当前用户
      if (props.currentUserId && !formData.reporter_id) {
        formData.reporter_id = props.currentUserId
      }
    }
  }
)

watch(
  () => props.currentUserId,
  (userId) => {
    // 当 currentUserId 变化时，如果 reporter_id 为空，则设置为当前用户
    if (userId && !formData.reporter_id) {
      formData.reporter_id = userId
    }
  },
  { immediate: true }
)

watch(
  () => props.defaultProjectId,
  (value) => {
    if (value && !formData.project_id) {
      formData.project_id = value
    }
  },
  { immediate: true }
)

watch(
  () => props.statusOptions,
  (options) => {
    if (options.length > 0 && !formData.status) {
      formData.status = options[0].value
    }
  },
  { immediate: true }
)

watch(
  () => props.priorityOptions,
  (options) => {
    if (options.length > 0 && !formData.priority) {
      formData.priority = options[0].value as RequirementPriority
    }
  },
  { immediate: true }
)
</script>

<style scoped lang="scss">
.create-requirement-dialog {
  :deep(.el-dialog) {
    max-height: 90vh;
    display: flex;
    flex-direction: column;
  }

  :deep(.el-dialog__header) {
    padding: 0;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }

  :deep(.el-dialog__title) {
    display: none;
  }

  :deep(.el-dialog__body) {
    padding: 24px;
    flex: 1;
    min-height: 0;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }
}

.create-requirement {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
}

.detail-body {
  display: flex;
  gap: 24px;
  flex: 1;
  min-height: 0;
  overflow: hidden;
  align-items: flex-start;
}

.primary-column {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
  overflow-y: auto;
  padding-right: 8px;
  min-height: 0;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
  }
}

.detail-header {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 16px;
}

.header-top {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.status-tags {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.title-section {
  margin-bottom: 8px;
}

.title-input {
  width: 100%;
}

.section-card {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 12px;
  padding: 0;
  display: flex;
  flex-direction: column;
  gap: 16px;
  box-shadow: 0 4px 12px rgba(31, 56, 88, 0.05);
}

.tabs-card {
  padding: 0;
}

.content-tabs {
  :deep(.el-tabs__header) {
    margin: 0;
    padding: 0 24px;
    border-bottom: 1px solid #ebeef5;
  }

  :deep(.el-tabs__content) {
    padding: 0;
  }
  
  :deep(.el-tab-pane) {
    padding: 24px;
  }
}

.tab-content-wrapper {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.side-column {
  width: 400px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  padding: 24px;
  position: sticky;
  top: 0;
  align-self: flex-start;
  gap: 16px;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }
}

.info-card {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 12px;
  padding: 18px 20px;
  display: flex;
  flex-direction: column;
  gap: 14px;
  box-shadow: 0 4px 12px rgba(31, 56, 88, 0.05);
}

.info-card-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
}

.info-form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-label {
  color: #909399;
  font-size: 13px;
}

.required {
  color: #f56c6c;
  margin-left: 4px;
}

.field-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
  font-weight: 500;
}

.field-error {
  :deep(.el-input__wrapper) {
    border-color: #f56c6c !important;
    box-shadow: 0 0 0 1px #f56c6c inset !important;
  }
  
  :deep(.el-select__wrapper) {
    border-color: #f56c6c !important;
    box-shadow: 0 0 0 1px #f56c6c inset !important;
  }
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 4px;
  line-height: 1.5;
}

.dialog-header-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 20px 24px;
  position: relative;
}

.dialog-header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
}

.dialog-header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-left: auto;
}

.associations-card {
  margin-top: 16px;
}

.association-sub-tabs {
  :deep(.el-tabs__header) {
    margin: 0;
  }

  :deep(.el-tabs__content) {
    padding: 0;
  }
}

.sub-tab-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;

  .header-info {
    .item-count {
      font-size: 15px;
      font-weight: 600;
      color: #303133;
    }
  }

  .header-actions {
    display: flex;
    gap: 8px;
  }
}

.items-list {
  min-height: 300px;
}

.parent-info-display {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 6px;
  
  .el-tag {
    display: flex;
    align-items: center;
    gap: 4px;
  }
  
  .parent-hint {
    font-size: 13px;
    color: #909399;
  }
}

.user-select-wrapper {
  position: relative;
  
  :deep(.el-select) {
    width: 100%;
    
    &.has-selected-user {
      .el-input__wrapper {
        .el-input__inner {
          color: transparent !important;
          text-shadow: none !important;
          caret-color: transparent;
        }
        
        .el-input__inner::placeholder {
          color: transparent !important;
        }
      }
      
      // 隐藏选择器内部显示的文本
      .el-select__selected-item {
        display: none !important;
        opacity: 0 !important;
        visibility: hidden !important;
      }
      
      // 隐藏输入框中的文本
      .el-input__suffix {
        .el-select__caret {
          margin-left: 0;
        }
      }
    }
  }
  
  .selected-user-overlay {
    position: absolute;
    left: 12px;
    top: 50%;
    transform: translateY(-50%);
    z-index: 10;
    pointer-events: none;
    display: flex;
    align-items: center;
    max-width: calc(100% - 50px);
    overflow: hidden;
    height: 20px;
    
    // 确保文本不会溢出
    .user-display {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 100%;
      
      .user-display-name {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }
}

@media (max-width: 992px) {
  .create-body {
    flex-direction: column;
  }

  .side-column {
    width: 100%;
    border-left: none;
    border-top: 1px solid #ebeef5;
    padding-left: 0;
    padding-top: 16px;
  }
}
</style>

